const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// 使用命令行方式复制文件，更简单直接
console.log('开始构建完整的部署包...');

try {
  // 首先清空dist目录
  console.log('清空dist目录...');
  if (fs.existsSync('./dist')) {
    fs.rmSync('./dist', { recursive: true, force: true });
  }
  fs.mkdirSync('./dist', { recursive: true });
  
  // 先执行JavaScript构建
  console.log('构建JavaScript文件...');
  execSync('npm run build', { stdio: 'inherit' });
  
  // 然后复制index.html
  console.log('复制index.html...');
  fs.copyFileSync('./index.html', './dist/index.html');
  
  // 复制customize.json配置文件
  console.log('复制customize.json...');
  fs.copyFileSync('./customize.json', './dist/customize.json');
  
  // 创建并复制fonts目录
  console.log('复制fonts目录...');
  fs.mkdirSync('./dist/fonts', { recursive: true });
  fs.copyFileSync('./fonts/LXGWWenKai-Regular.ttf', './dist/fonts/LXGWWenKai-Regular.ttf');
  
  // 创建并复制img目录
  console.log('复制img目录...');
  fs.mkdirSync('./dist/img', { recursive: true });
  const imgFiles = fs.readdirSync('./img');
  imgFiles.forEach(file => {
    fs.copyFileSync(`./img/${file}`, `./dist/img/${file}`);
    console.log(`  复制文件: ${file}`);
  });
  
  // 创建并复制music目录
  console.log('复制music目录...');
  fs.mkdirSync('./dist/music', { recursive: true });
  fs.copyFileSync('./music/bgMusic.mp3', './dist/music/bgMusic.mp3');
  
  // 创建并复制script目录
  console.log('复制script目录...');
  fs.mkdirSync('./dist/script', { recursive: true });
  const scriptFiles = fs.readdirSync('./script');
  scriptFiles.forEach(file => {
    fs.copyFileSync(`./script/${file}`, `./dist/script/${file}`);
    console.log(`  复制文件: ${file}`);
  });
  
  // 创建并复制style目录
  console.log('复制style目录...');
  fs.mkdirSync('./dist/style', { recursive: true });
  const styleFiles = fs.readdirSync('./style');
  styleFiles.forEach(file => {
    fs.copyFileSync(`./style/${file}`, `./dist/style/${file}`);
    console.log(`  复制文件: ${file}`);
  });
  
  console.log('\n✅ 构建完成！所有文件已成功复制到dist目录。');
  
  // 显示dist目录内容
  console.log('\ndist目录内容:');
  const distContents = fs.readdirSync('./dist', { withFileTypes: true });
  distContents.forEach(item => {
    if (item.isDirectory()) {
      console.log(`📁 ${item.name}`);
      const subItems = fs.readdirSync(`./dist/${item.name}`);
      subItems.forEach(subItem => {
        console.log(`  └── ${subItem}`);
      });
    } else {
      console.log(`📄 ${item.name}`);
    }
  });
  
} catch (error) {
  console.error('❌ 构建过程中出现错误:', error.message);
  process.exit(1);
}